function setLocation(href){
    location.href = href;
}

String.prototype.trim = function(){
    return $.trim(this);
};

String.prototype.format = function(args){
    var str = this;
    var arr = str.match(/\{(\w+)\}/gi);
    for(var i = 0; i < arr.length; i++){
        var l = arr[i].length;
        str = str.replace(arr[i], args[arr[i].substring(1, l - 1)]);
    }
    return str;
};

String.prototype.pad = function(len, flag, type){
    var str = this;
    if(str.length < len){
        while(str.length < len){
            switch(type){
                case 'l':
                    str = flag + str;
                    break;
                case 'r':
                    str = str + flag;
                    break;
                default:
                    str = str + flag;
                    break;
            }
        }
    }
    return str;
};

jQuery.validator.addMethod('character', function(value){
    return /^\w+$/.test(value);
});

jQuery.validator.addMethod('rangeLength', function(value, element, params){
    return value.length >= params[0] && value.length <= params[1];
});

var Kdf = {
    extend: function(bc, sc, o) {
        var f = function() {};
        f.prototype = sc.prototype;
        bc.prototype = new f();
        bc.prototype.constructor = bc;
        bc.superclass = sc.prototype;
        for (var m in o){
            bc.prototype[m] = o[m];
        }
    },

    setScope: function(callback, scope) {
        return function() {
            return callback.apply(scope, arguments);
        };
    },

    namespace: function() {
        var ns, d;
        for (var i = 0; i < arguments.length; i++) {
            ns = window;
            d = arguments[i].split(".");
            for (var j in d){
                ns = ns[d[j]] = ns[d[j]] ? ns[d[j]] : {};
            }
        }
    },

    isObject: function(obj) {
        return (obj && obj.constructor && obj.constructor == Object.prototype.constructor && !obj.nodeName)
        ? true : false;
    },

    globals:{
        forms:[],
        grids:[]
    },

    copyright: 'Keep Doing Studio'
};

Kdf.Base = function() {
    if (Kdf.isObject(arguments[0])) {
        var config = arguments[0];
        Kdf.Base.superclass.init.call(this);
        this.initialize(config);
    } else {
        arguments.length > 0?
        Kdf.Base.superclass.init.apply(this, arguments):
        Kdf.Base.superclass.init.call(this);
    }
};

Kdf.extend(Kdf.Base, jQuery, {
    initialize: function(config) { }
});

Kdf.Ajax = {};
Kdf.Ajax.processResult = function(data, textStatus, request, setting){
    //    var json = eval(data);
    //    switch(json.status){
    //        case 'fail':
    //            Kdf.Ajax.processFailResult?
    //            Kdf.Ajax.processFailResult(data):
    //            json.message? alert(json.message): alert('fail');
    //            return false;
    //        case 'reject':
    //            if(Kdf.Ajax.processRejectResult){
    //                Kdf.Ajax.processRejectResult(data);
    //            }else{
    //                json.url?
    //                top.location = json.url:
    //                json.message? alert(json.message): alert('reject');
    //            }
    //            return false;
    //        case 'login':
    //            Kdf.Ajax.processLoginResult?
    //            Kdf.Ajax.processLoginResult(data):
    //            alert('login');
    //            return false;
    //    }
    //
    setting.resultHandler(data);
    return true;
};

Kdf.Ajax.processError = function(request, textStauts){
    alert(request.statusText);
};

Kdf.Ajax.load = function(setting){
    var config = jQuery.extend({}, {
        data:{},
        dataType:'text',
        method:'GET',
        cache: false
    }, setting);
    if(!config.resultHandler){
        config.resultHandler = function(data){
            config.success(data);
        };
    }

    jQuery.ajax({
        url:config.url,
        data:config.data,
        dataType:config.dataType,
        method:config.method,
        success:function(data, textStatus, request){
            Kdf.Ajax.processResult(data, textStatus, request, setting);
        },
        error:function(request, textStatus, errorThrown){
            Kdf.Ajax.processError(request, textStauts, errorThrown);
        }
    });
};

Kdf.Ajax.loadJson = function(setting){
    setting.dataType = 'text';
    setting.resultHandler = function(data){
        var json = eval('(' + data + ')');
        setting.success(json);
    };
    Kdf.Ajax.load(setting);
};

Kdf.Ajax.loadHtml = function(setting){
    setting.dataType = 'html';
    setting.resultHandler = function(data){
        setting.success(data);
    };
    Kdf.Ajax.load(setting);
};

Kdf.Ui = {};
Kdf.Ui.getForm = function(formId){
    return Kdf.globals.forms[formId];
};

Kdf.Ui.getGrid = function(gridId){
    return Kdf.globals.grids[gridId];
};

Kdf.Ui.submitForm = function(formId, url){
    if(url){
        kdf.getForm(formId).setAction(url);
    }
    kdf.getForm(formId).submit();
};

Kdf.Ui.Form = function(){
    this.form = null;
    this.validator = null;
    Kdf.Ui.Form.superclass.constructor.apply(this, arguments);
};

Kdf.extend(Kdf.Ui.Form, Kdf.Base, {
    initialize:function(setting){
        Kdf.Ui.Form.superclass.initialize.apply(this, arguments);
        this.setting = this.extend({}, {
            validate:true,
            ajax:false
        }, setting);
        this.form = jQuery(setting.form);
    //		this.form.bind('submit', Kdf.setScope(this.submit, this));
    //		if(setting.applyButton){
    //			jQuery(applyButton).click(function(){
    //				this.apply();
    //			});
    //		}
    //		if(setting.saveButton){
    //			jQuery(saveButton).click(function(){
    //				this.save();
    //			});
    //		}
    },

    setAction:function(url){
        this.form.attr('action', url);
        return this;
    },

    setHidden:function(name, value){
        this.form.find("input[name='" + name + "']").remove();
        if($.isArray(value)){
            for(var i = 0; i < value.length; i++){
                this.form.append('<input type="hidden" name="' + name + '" value="' + value[i] + '"/>');
            }
        }else{
            this.form.append('<input type="hidden" name="' + name + '" value="' + value + '"/>');
        }
        return this;
    },

    clearBackgroundText:function(){
        this.form.find(':text[backgroundText]').each(function(){
            $this = jQuery(this);
            if($this.val() == $this.attr('backgroundText')){
                $this.val('');
            }
        });
    },

    submit:function(action){
        if(this.setting.validate){
            jQuery.metadata.setType('attr', 'validate');
            this.clearBackgroundText();
            if(this.beforeValidate){
                this.beforeValidate(this);
            }
            if(!this.form.validate({onkeyup:false}).form()){
                if(this.validateFail){
                    this.validateFail(this);
                }
                return false;
            }
        }

        if(this.beforeSubmit){
            if(!this.beforeSubmit(this)){
                return false;
            }
        }

        if(action){
            this.setAction(action);
        }

        if(this.form.attr('method').toLowerCase() == 'get'){
            var args = this.form.serialize().split('&');
            var argString = '';
            for(var i = 0; i < args.length; i++){
                var argItem = args[i].split('=');
                if(jQuery.trim(argItem[1]).length > 0){
                    argString += '/' + argItem[0] + '/' + argItem[1];
                }
            }
            var action = this.form.attr('action');
            if(action.substr(action.length, 1) == '/'){
                action = action.substr(0, action.length - 1);
            }
            action += argString;
            this.form.attr('action', action);
            location.href = action;
            return false;
        }

        if(this.setting.ajax){
            this.form.ajaxSubmit();
            return false;
        }

        this.form.submit();
        return true;
    },

    save:function(){
        if(this.form.find('#apply').length > 0){
            this.form.find('#apply').val('');
        }
        this.submit();
    },

    apply:function(){
        var h = this.form.find('#apply').length > 0?
        this.form.find('#apply'):
        jQuery('<input type="hidden" id="apply" name="apply"/>').appendTo(this.form);
        h.val('1');
        this.submit();
    }
});

Kdf.Ui.Grid = function(){
    this.grid = null;
    this.setting = null;
    this.head = null;
    this.body = null;
    this.footer = null;
    this.rows = null;
    Kdf.Ui.Grid.superclass.constructor.apply(this, arguments);
};

Kdf.extend(Kdf.Ui.Grid, Kdf.Base, {
    initialize: function(setting){
        Kdf.Ui.Grid.superclass.initialize.apply(this, arguments);
        this.setting = this.extend({},{
            rowCheckBox:'.row-check',
            rowHoverStyle:'hover',
            rowSelectedStyle:'selected'
        },
        setting);
        this.grid = jQuery(this.setting.grid);
        this.head = jQuery(this.grid.find('thead')[0]);
        this.body = jQuery(this.grid.find('tbody')[0]);
        this.footer = jQuery(this.grid.find('tfooter')[0]);
        this.rows = this.body.children('tr');

        this.rows.bind('mouseenter', Kdf.setScope(this.onRowMouseEnter, this))
        .bind('mouseleave', Kdf.setScope(this.onRowMouseLevel, this));
        jQuery(this.setting.rowCheckBox).bind('click', Kdf.setScope(this.onRowCheckBoxClick, this));
    },

    onRowMouseEnter:function(event){
        jQuery(event.currentTarget).addClass(this.setting.rowHoverStyle);
    },

    onRowMouseLevel:function(event){
        jQuery(event.currentTarget).removeClass(this.setting.rowHoverStyle);
    },

    onRowCheckBoxClick:function(event){
        var $this = jQuery(event.currentTarget);
        $this.attr('checked')?
        $this.parent().parent().addClass(this.setting.rowSelectedStyle):
        $this.parent().parent().removeClass(this.setting.rowSelectedStyle);
    },

    selectAll:function(){
        jQuery(this.setting.rowCheckBox).attr('checked', 'checked');
        this.rows.addClass(this.setting.rowSelectedStyle);
    },
    selectInverse:function(){
        var s = this.setting.rowSelectedStyle;
        jQuery(this.setting.rowCheckBox).each(function(){
            $this = jQuery(this);
            $this.attr('checked')?
            $this.removeAttr('checked').parent().parent().removeClass(s):
            $this.attr('checked', true).parent().parent().addClass(s);
        });
    },
    cancelSelected:function(){
        jQuery(this.setting.rowCheckBox).removeAttr('checked');
        this.rows.removeClass(this.setting.rowSelectedStyle);
    },
    hasSelectedRow:function(){
        return jQuery(this.setting.rowCheckBox + ':checked').length > 0;
    }
});

jQuery(function(){
    jQuery(':text[backgroundText]').each(function(){
        $this = jQuery(this);
        if(jQuery.trim($this.val()).length == 0){
            $this.val($this.attr('backgroundText')).addClass('text-backgroundtext');
        }
        $this.bind('focus.backgroundText', function(){
            $this = jQuery(this).addClass('text-hover');
            if($this.val() == $this.attr('backgroundText')){
                $this.val('');
            }
        }).bind('blur.backgroundText', function(){
            $this = jQuery(this).removeClass('text-hover');
            if(jQuery.trim($this.val()).length == 0){
                $this.val($this.attr('backgroundText')).addClass('text-backgroundtext');
            }else{
                $this.removeClass('text-backgroundtext');
            }
        });
    });

    jQuery('form[setting]').each(function(){
        Kdf.globals.forms[jQuery(this).attr('id')] = new Kdf.Ui.Form({
            form:this
        });
    });
    jQuery('table.grid').each(function(){
        Kdf.globals.grids[jQuery(this).attr('id')] = new Kdf.Ui.Grid({
            grid:this
        });
    });
    jQuery('input.datetime').each(function(){
        $(this).datepicker();
    });
});

function deleteGridChecked(gridId, url){
    var grid = Kdf.Ui.getGrid(gridId);
    if(grid.hasSelectedRow()){
        if(confirm(Language.messages.confirmDelete)){
            var formId = $('#' + gridId).parent('form').attr('id');
            Kdf.Ui.getForm(formId).setAction(url).submit();
        }
    }else{
        alert(Language.messages.selectGridItem);
    }
}

function submitGridChecked(gridId, url){
    var grid = Kdf.Ui.getGrid(gridId);
    if(grid.hasSelectedRow()){
        var formId = $('#' + gridId).parent('form').attr('id');
        Kdf.Ui.getForm(formId).setAction(url).submit();
    }else{
        alert(Language.messages.selectGridItem);
    }
}

function forbidGridChecked(gridId, url){
    var grid = Kdf.Ui.getGrid(gridId);
    if(grid.hasSelectedRow()){
        var formId = $('#' + gridId).parent('form').attr('id');
        var html = '<div id="status_message_container"><textarea id="status_message" name="statusmessage" style="width:100%;height:80px;"/></div>'
        $(html).dialog({
            width:300,
            title: '原因',
            modal: true,
            resizable: false,
            draggable: false,
            buttons:{
                '提交':function(){
                    $(this).dialog( "destroy" );
                    $('#status_message').appendTo('#' + formId).hide();
                    Kdf.Ui.getForm(formId).setAction(url).submit();
                },
                '取消':function(){
                    $(this).dialog( "destroy" );
                    $('#status_message_container').remove();
                }
            }
        });
//        Kdf.Ui.getForm(formId).setAction(url).submit();
    }else{
        alert(Language.messages.selectGridItem);
    }
}

function submitPublish(formId, url){
    Kdf.Ui.getForm(formId).setAction(url).submit();
}

function submitForbid(formId, url){
    var html = '<div id="status_message_container"><textarea id="status_message" name="statusmessage" style="width:100%;height:80px;"/></div>'
    $(html).dialog({
        width:300,
        title: '原因',
        modal: true,
        resizable: false,
        draggable: false,
        buttons:{
            '提交':function(){
                $(this).dialog( "destroy" );
                $('#status_message').appendTo('#' + formId).hide();
                Kdf.Ui.getForm(formId).setAction(url).submit();
            },
            '取消':function(){
                $(this).dialog( "destroy" );
                $('#status_message_container').remove();
            }
        }
    });
}

function showFileBrowser(setting){
    Kdf.Ajax.loadHtml({
        url:pageInfo.routeBaseUrl + 'filebrowser/index/index',
        data:{
            'title':setting.title,
            'path':setting.path,
            'filetype':setting.filetype,
            'files':setting.files,
            'callback':setting.callback,
            'rnd':Math.random()
        },
        success:function(data){
            $('body').append(data);
        }
    });
}

function choosePoiDialog(args){
    var url = pageInfo.routeBaseUrl + 'foundation/helper/poi-browser';
//    setting = $.extend({}, {}, setting);
    $.ajax({
        url:url,
        data:args,
        dataType: 'html',
        method: 'POST',
        success:function(data){
            $('body').append(data);
        }
    });
}

function chooseRoadDialog(setting){
    var url = pageInfo.routeBaseUrl + 'foundation/helper/choose-road';
    setting = $.extend({}, {}, setting);
    $.ajax({
        url:url,
        data:setting,
        dataType: 'html',
        method: 'POST',
        success:function(data){
            $('body').append(data);
        }
    });
}

function chooseConcessionsDialog(setting){
    var url = pageInfo.routeBaseUrl + 'promotion/helper/choose-concessions';
    setting = $.extend({}, {}, setting);
    $.ajax({
        url:url,
        data:setting,
        dataType: 'html',
        method: 'POST',
        success:function(data){
            $('body').append(data);
        }
    });
}

function chooseArticleDialog(setting){
    var url = pageInfo.routeBaseUrl + 'article/helper/choose-article';
    setting = $.extend({}, {}, setting);
    $.ajax({
        url:url,
        data:setting,
        dataType: 'html',
        method: 'POST',
        success:function(data){
            $('body').append(data);
        }
    });
}

var currentPoiBrowserSetting = null;
function showPoiBrowser(setting){
    currentPoiBrowserSetting = setting;
    var selected = [];
    $('#' + setting.container + ' input[name="' + setting.name + '"]').each(function(){
        selected.push($(this).val());
    });

    if(setting.configFunction){
        setting.configFunction(setting);
    }
    if(!setting.callbackFunction){
        setting.callbackFunction = 'showPoiBrowserCallback';
    }
    var args = 'rmd=' + Math.random()  + '&options[callback]=' + setting.callbackFunction;
    if(selected.length > 0){
        for(var i = 0; i < selected.length; i++){
            args += '&ignores[]=' + selected[i];
        }
    }
    
    if(setting.filter){
        for(var i in setting.filter){
            args += '&filter[' + i + ']=' + setting.filter[i];
        }
    }
    choosePoiDialog(args);
}

function showPoiBrowserCallback(data){
    var html = '<li id="poi' + data.id + '"><span>' + data.text + '</span>';
    html += '<a href="javascript:void(0)" onclick="javascript:deletePoiSelected(this)">' + Language.buttons['remove'] + '</a>';
    html += '<input type="hidden" name="' + currentPoiBrowserSetting.name + '" value="' + data.id + '"</li>';
    $('#' + currentPoiBrowserSetting.container).append(html);
    $('#' + currentPoiBrowserSetting.id).val('1');
}

function deletePoiSelected(el){
    $(el).parent().remove();
    if($('#' + currentPoiBrowserSetting.container + ' input[name="' + currentPoiBrowserSetting.name + '"]').length == 0){
        $('#' + currentPoiBrowserSetting.id).val('');
    }
}

function showArticleBrowser(){
    chooseArticleDialog({'callback':'showArticleCallback'});
}

function deleteFile(fileUrl, callback){
    var url = pageInfo.routeBaseUrl + 'filemanage/file/delete';
    $.ajax({
        url:url,
        data:{'fileurl':fileUrl},
        dataType: 'json',
        method: 'GET',
        success:function(data){
            if(callback){
				callback(data);
			}
        }
    });	
}